<template>
    <div class="login-account">
        <el-form ref="formRef" :model="account" :rules="rules" label-width="100" label-position="left">
            <el-form-item label="用户名" prop="loginName">
                <el-input v-model="account.loginName"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="account.password" type="password"></el-input>
            </el-form-item>
        </el-form>
        <div class="account-control">
            <el-checkbox v-model="rememberMe">记住我</el-checkbox>
            <el-link href="#" type="primary">忘记密码</el-link>
        </div>
        
        <el-button type="primary" class="login-btn" :loading="submitting" @click="loginAction">登录</el-button>
    </div>
</template>

<script lang="ts" setup>
import { ElForm, ElMessage, type FormRules } from 'element-plus'
import * as api from '@/api/auth'
import type { LoginFormType } from '@/api/auth/types'

const emit = defineEmits(['onSuccess'])

const formRef = ref<InstanceType<typeof ElForm>>()

const rememberMe = ref(false)
const submitting = ref(false)

const account = reactive<LoginFormType>({
    loginName: '',
    password: ''
})

const rules = reactive<FormRules>({
    loginName: [
        {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
        }
    ],
    password: [
        {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
        }
    ]
})

const loginAction = () => {
    formRef.value?.validate((valid) => {
        if(valid) {
            submitting.value = true

            api.login(account).then((res) => {
                if(res.success) {
                    // 登录成功
                    ElMessage({
                        message: '登录成功',
                        type: 'success',
                    })
                    submitting.value = false

                    emit('onSuccess', res.data)
                } else {
                    // 登录失败
                    ElMessage.error(res.message)
                }
            }).catch((error) => {
                ElMessage.error(error.message)
                submitting.value = false
            })
        }
    })
}

defineExpose({
    loginAction
})
</script>

<style lang="scss" scoped>
.account-control {
    margin-top: 10px;
    display: flex;
    justify-content: space-between;
}
.login-btn {
    width: 100%;
    margin-top: 10px;
}
</style>